package user

import (
	"context"
	"encoding/json"
	"errors"
	"hzjt-oam/rpc/sys/pb"
	"strconv"
	"time"

	"hzjt-oam/admin/internal/svc"
	"hzjt-oam/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserAddLogic) UserAdd(req *types.AddUserReq) (resp *types.AddUserResp, err error) {

	userId, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, errors.New("验证token未通过")
	}
	user_one, err := l.svcCtx.UserSrv.GetSysUserById(l.ctx, &pb.GetSysUserByIdReq{
		Id: int64(userId),
	})
	l.svcCtx.UserSrv.AddSysUser(l.ctx, &pb.AddSysUserReq{
		Name:           req.Name,
		NickName:       req.NickName,
		Password:       req.Password,
		Salt:           "",
		Email:          req.Email,
		Mobile:         req.Mobile,
		Status:         req.Status,
		DeptId:         req.DeptId,
		CreateBy:       user_one.SysUser.Name,
		LastUpdateBy:   user_one.SysUser.Name,
		LastUpdateTime: time.Now().Unix(),
		DelFlag:        0,
		RoleId:         req.RoleId,
	})

	if err != nil {
		logx.WithContext(l.ctx).Errorf("根据userId: %s,查询用户异常:%s", strconv.FormatInt(int64(userId), 10), err.Error())
		return nil, errors.New("查询用户失败")
	}

	return &types.AddUserResp{"成功"}, err
}
